package com.lnking.lnkingplace.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lnking.lnkingplace.Util.UserUtil;
import com.lnking.lnkingplace.mapper.PlaceInfoMapper;
import com.lnking.lnkingplace.mapper.UserMapper;
import com.lnking.lnkingplace.model.dto.place.PlaceCountDto;
import com.lnking.lnkingplace.model.dto.place.PlaceExportDto;
import com.lnking.lnkingplace.model.dto.place.PlacePositionDto;
import com.lnking.lnkingplace.model.entity.IsolationPlace;
import com.lnking.lnkingplace.model.entity.PlaceInfo;
import com.lnking.lnkingplace.model.entity.User;
import com.lnking.lnkingplace.model.enums.ProcessStatus;
import com.lnking.lnkingplace.model.enums.UserType;
import com.lnking.lnkingplace.model.request.place.*;
import com.lnking.lnkingplace.service.IPlaceInfoService;
import com.lnking.starter.export.utils.ExportUtils;
import com.lnking.starter.mybatis.entity.IPageInfo;
import com.lnking.starter.mybatis.entity.Page;
import com.lnking.starter.mybatis.mapper.CustomBaseMapper;
import com.lnking.starter.mybatis.service.impl.CustomServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhangqt
 * @since 2022-08-18
 */
@Service
public class PlaceInfoServiceImpl extends CustomServiceImpl<PlaceInfoMapper, PlaceInfo> implements IPlaceInfoService {
    @Resource
    UserMapper userMapper;

    @Resource
    UserUtil userUtil;

    /**
     * 初始密码
     */
    final String PWD = "123456";
    public static final String YEAR = "年";
    /**
     * 去年，上个月
     */
    public static final long LAST = 1L;
    public static final Integer NUM = 0;

    @Override
    public List<PlaceCountDto> queryStreetCount(String street) {
        return this.baseMapper.queryStreetCount(street, userUtil.getUser().getChannel());
    }

    @Override
    public List<PlaceCountDto> queryCount(String street) {
        String channel = userUtil.getUser().getChannel();
        List<PlaceCountDto> result = this.baseMapper.queryCount(street, channel);
        return result;
    }

    @Override
    public List<String> getType() {
        return this.baseMapper.getType();
    }

    @Override
    public List<String> getStreet() {
        return this.baseMapper.getStreet();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        //判断角色
//        String type = userUtil.getUser().getType();
//
//        //网格员
//        if(UserType.STREET.equals(type)){
//            //只能删除未通过的
//            this.baseMapper.updateDelFlag(ProcessStatus.PENDING_REVIEW,id);
//        }
//        //监管员
//        else if(UserType.SUPERVISE.equals(type)){
//            //直接删除
//            this.removeById(id);
//            isolationPlaceMapper.updateDelFlag(id);
//        }
        //先删除user
        userMapper.updateDelFlag(id);
        //删除place
        PlaceInfo info = new PlaceInfo();
        info.setId(id);
        info.setDelTime(LocalDateTime.now());
        this.updateById(info);
        this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(PlaceAddRequest params) throws Exception {
        //验证场所名称是否存在
        String placeName = params.getPlaceName();

        PlaceInfo checkName = checkName(placeName);
        Assert.isTrue(null == checkName, "该场所已存在");

        PlaceInfo checkPhone = checkPhone(params.getLinkmanPhone());
        Assert.isTrue(null == checkPhone, "手机号已存在");

        PlaceInfo placeInfo = new PlaceInfo();
        BeanUtils.copyProperties(params, placeInfo);
        placeInfo.setCreateTime(LocalDateTime.now());

        //获取渠道
        String channel = userUtil.getUser().getChannel();
        placeInfo.setChannel(channel);

        String type = userUtil.getUser().getType();
        //网格员
        if (UserType.STREET.equals(type)) {
            //需要审批
            placeInfo.setProcessAddStatus(ProcessStatus.PENDING_REVIEW);
            this.baseMapper.insert(placeInfo);
        }
        //监管员
        else if (UserType.SUPERVISE.equals(type)) {
            placeInfo.setProcessAddStatus(ProcessStatus.PASSED);
            this.baseMapper.insert(placeInfo);
            //场所联系人
            String linkman = placeInfo.getLinkman();
            //联系电话
            String phoneNumber = placeInfo.getLinkmanPhone();

            //联系电话不为空才绑定
            if (StringUtils.isNotBlank(phoneNumber)) {
                Integer count = this.checkUser(phoneNumber);
                Assert.isTrue(count == 0, "手机号码已存在");

                User user = getUserInfo(linkman, phoneNumber, placeInfo.getId());
                userMapper.insert(user);
            }
        }
        // 配置核酸
        getBaseMapper().insertPlaceConfig(placeInfo.getId(), params.getConfigDay());
    }

    private PlaceInfo checkName(String placeName) {
        QueryWrapper<PlaceInfo> query = new QueryWrapper<>();
        query.lambda().eq(PlaceInfo::getPlaceName, placeName);
        PlaceInfo info = this.baseMapper.selectOne(query);
        return info;
    }

    private PlaceInfo checkPhone(String phone) {
        QueryWrapper<PlaceInfo> query = new QueryWrapper<>();
        query.lambda().eq(PlaceInfo::getLinkmanPhone, phone);
        PlaceInfo info = this.baseMapper.selectOne(query);
        return info;
    }

    private User getUserInfo(String linkman, String phoneNumber, String id) {
        User user = new User();
        user.setName(linkman);
        user.setPhone(phoneNumber);
        user.setPassword(DigestUtils.sha1Hex(PWD));
        user.setType(UserType.LOCATION);
        user.setPlaceId(id);
        user.setChannel(userUtil.getUser().getChannel());
        return user;
    }

    private Integer checkUser(String phone) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.lambda().eq(User::getPhone, phone);
        return userMapper.selectCount(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PlaceUpdateRequest params) throws Exception {
        PlaceInfo checkName = checkName(params.getPlaceName());
        Assert.isTrue(null == checkName ||
                checkName.getId().equals(params.getId()), "该场所已存在");

        PlaceInfo placeInfo = new PlaceInfo();
        BeanUtils.copyProperties(params, placeInfo);
        this.baseMapper.updateById(placeInfo);
        // 查询用户数量 在岗人数不能超过用户数量
        QueryWrapper<User> Swapper = new QueryWrapper<>();
        Swapper.lambda().eq(User::getPlaceId, placeInfo.getId());
        Integer integer = userMapper.selectCount(Swapper);
        if (params.getWorkerNum() != null) {
            Assert.isTrue(params.getWorkerNum() <= integer, "在岗人数不能超过从业人数");
        }
        getBaseMapper().deletePlaceConfig(params.getId());
        getBaseMapper().insertPlaceConfig(params.getId(), params.getConfigDay());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProcessAddStatus(PlaceUpdateProcessAddStatus params) {
        PlaceInfo placeInfo = new PlaceInfo();
        BeanUtils.copyProperties(params, placeInfo);
        placeInfo.setAuditAddUser(userUtil.getUser().getName());
        if (ProcessStatus.PASSED.equals(params.getProcessAddStatus())) {
            placeInfo.setAuditTime(LocalDateTime.now());
        }
        this.updateById(placeInfo);

        //通过后添加用户信息
        if (ProcessStatus.PASSED.equals(params.getProcessAddStatus())) {
            PlaceInfo data = this.baseMapper.selectById(params.getId());
            if (StringUtils.isNotBlank(data.getLinkmanPhone())) {
                Integer count = this.checkUser(data.getLinkmanPhone());
                Assert.isTrue(count == 0, "手机号码已存在");

                User user = getUserInfo(data.getLinkman(), data.getLinkmanPhone(), data.getId());
                userMapper.insert(user);
            }
        }
    }

    @Override
    public void exportExcel(PlaceListRequest params, HttpServletResponse response) throws Exception {
//        UserDto userInfo = userUtil.getUser();
        params.setChannel("文创局");
        List<PlaceExportDto> exportData = this.baseMapper.queryExportData(params);
        ExportUtils.export(exportData, response, PlaceExportDto.class);
    }

    @Override
    public void updateOperatingStatus(PlaceUpdateStatusRequest params) {
        PlaceInfo placeInfo = new PlaceInfo();
        BeanUtils.copyProperties(params, placeInfo);
        this.updateById(placeInfo);
    }

    @Override
    public PlaceInfo getDetails(String id) {
        return this.baseMapper.getDetail(id);
    }

    @Override
    public PlaceInfo check(String placeName) {
        LambdaQueryWrapper<PlaceInfo> query = new LambdaQueryWrapper<>();
        query.eq(PlaceInfo::getPlaceName, placeName);
        PlaceInfo info = this.baseMapper.selectOne(query);
        return info;
    }

    @Override
    public void set() {

    }

    @Override
    public List<PlacePositionDto> getPosition(String type, String street) {

        return getBaseMapper().getPosition(type, street);
    }

    @Override
    public Object managementList(ManagementPlaceListRequest params) {
        List list;
        if (params.isPage()) {
            PageHelper.startPage(params.getPageNum(), params.getPageSize());
            list =  this.getBaseMapper().managementList(params);
            PageInfo<Object> page = new PageInfo(list);
            return new IPageInfo(page);
        } else {
            list = this.getBaseMapper().managementList(params);
            return list;
        }
    }


}
